import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import VideoDetailView from '../views/VideoDetailView.vue'
import CategoryView from '../views/CategoryView.vue'
import LoginView from '../views/LoginView.vue'
import RegisterView from '../views/RegisterView.vue'
import UserProfileView from '../views/UserProfileView.vue'
import SearchView from '../views/SearchView.vue'

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/video/:id',
    name: 'videoDetail',
    component: VideoDetailView,
    props: true
  },
  {
    path: '/category/:id?',
    name: 'category',
    component: CategoryView,
    props: true
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView,
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    name: 'register',
    component: RegisterView,
    meta: { requiresAuth: false }
  },
  {
    path: '/profile',
    name: 'profile',
    component: UserProfileView,
    meta: { requiresAuth: true }
  },
  {
    path: '/search',
    name: 'search',
    component: SearchView
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL || '/'),
  routes
})

// 路由守卫：处理需要登录的页面
router.beforeEach((to, from, next) => {
  const requiresAuth = to.meta.requiresAuth
  const isLoggedIn = localStorage.getItem('userToken') // 简单的登录状态检查
  
  if (requiresAuth === true && !isLoggedIn) {
    // 需要登录但未登录，重定向到登录页面
    next({ name: 'login', query: { redirect: to.fullPath } })
  } else if ((to.name === 'login' || to.name === 'register') && isLoggedIn) {
    // 已登录，访问登录/注册页面时重定向到首页
    next({ name: 'home' })
  } else {
    // 其他情况正常通过
    next()
  }
})

export default router